<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="@{/}">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />

<th:block th:include ="commHeaderInclude::commHead"></th:block>
<script th:src="@{/js/Certificate.js}"></script>
<script th:src="@{/js/Cryptokit.js}"></script>
<style>
article {
	padding: 0 6.25rem;
}
article h2 {
	font-size: 24px;
	line-height: 50px;
	font-weight: bold;
}
article p {
	font-size: 14px;
	line-height: 32px;
	text-indent: 2em;
}
article div p {
	font-size: 12px;
	line-height: 20px;
}
</style>
<title>签发授权书</title>
</head>
<body class="ht">
<th:block th:include="commHeaderInclude::loading"></th:block>
	<div class="content-wrapper">
		<form name="form" id="form" class="form" method="post" th:object="${vo.data}">
			<input type="hidden" id="signature" name="signature" value="" />
  			<input type="hidden" id="subjectDN" name="subjectDN" value="" />
  			<input type="hidden" id="sourceData" name="sourceData" value="" />
  			<input type="hidden" id="bankOrgId" name="bankOrgId" th:value="*{bankOrgId}" />
  			<input type="hidden" id="authStartTime" name="authStartTime" th:value="*{authStartTime}" />
  			<input type="hidden" id="authEndTime" name="authEndTime" th:value="*{authEndTime}" />
  			
			<article>
				<h2 class="text-center mb-2">医保信息查询授权书</h2>
				<p class="text-strong"><span>授权人：</span><span class="text-line" th:text="*{@util.fStr(miOrgName)}"></span></p>
				<p class="mb-3 text-strong"><span>被授权人：</span><span class="text-line" th:text="*{@util.fStr(bankName)}"></span></p>
				<p>为获取融资服务，现授权<span class="text-line ml-2 mr-2" th:text="*{@util.fStr(bankName)}"></span>（统一社会信用代码：<span class="text-line ml-2 mr-2" th:text="*{bankOrgCode}"></span>）通过<span class="text-strong">中征应收账款融资服务平台</span>查询、收集与我方有关的全部信息，包括但不限于：</p>
				<p>1.医疗保障局共享的机构主体、医保合作协议、医保结算信息等；</p>
				<p>2.卫生健康委员会共享的机构主体、许可证、经营概况等信息；</p>
				<p>3.市场监督管理局共享的机构主体信息；</p>
				<p>4.其他行政处罚信息；</p>
				<p>授权期限：<span class="text-line ml-2 mr-2" th:text="*{authStartTimeStr}" ></span>至<span class="text-line ml-2 mr-2" th:text="*{authEndTimeStr}"></span></p>
				<p>被授权人可对上述信息进行合理的使用，并可将上述信息传递给相关单位进行核验。为确保信息安全，被授权人应采取有效措施并承担保密义务。</p>
				<p class="mt-3 text-right text-strong"><span class="text-line" th:text="*{@util.fStr(miOrgName)}"></span></p>
				<div class="alert alert-warning mt-3">
					<p class="text-strong">请确认已完成以下事项：</p>
					<p class="mt-2">1) 已向中国金融认证中心申领电子证书；</p>
					<p class="mt-2">2) 已在平台“我的园地—数字证书绑定指引”页面安装数字证书驱动；</p>
					<p class="mt-2">3) 已在平台“我的园地—数字证书绑定指引”页面完成绑定；</p>
					<p class="mt-2">4) 插入数字证书；</p>
					<p class="mt-2">5) 中国金融认证中心（CFCA）数字证书签名确认方式支持在Edge浏览器（Edge80-最新）、非IE浏览器（360及搜狗中支持NPAPI的浏览器）、IE浏览器（IE10-11）下使用。</p>
				</div>
			</article>

			<div class="row">
				<input class="btn btn-primary btn-lg" type="button" id="confirmButton1" value="签名授权" />
				<input class="btn btn-primary btn-lg" type="button" id="confirmButton2" value="普通授权" />
			</div>
		</form>
	</div>
</body>

<script>
var browser = browserInfo();

var certificate = new Certificate();
certificate.init();
var cryptokit = new Cryptokit(browser.name);
cryptokit.init();

var bindCfca = '[[${vo.data.bindCfca}]]';

$("#confirmButton1").bind("click",function(event){
	var signType = $("input[name='signType']:checked").val();
	console.log(signType);
	
	if(window.confirm("是否确认签名?")){
		ht.loading.open();

		console.log("bindCfca="+bindCfca);

		if(bindCfca == "1"){
			alert("未检测到已绑定有效的证书，请确认是否插入已绑定有效的证书？");
			ht.loading.close();
			return false;
		}

		var subjectDN;
		var sealImage;

		var browser = browserInfo();
		if("Edge"==browser.name || "Edge(Chromium)"==browser.name){
			cryptokit.SelectCertificate().then(function (response) {

				cryptokit.GetSignCertInfo("SubjectDN").then(function(response){
					subjectDN = response.result;
					$("#subjectDN").val(subjectDN);
					console.log("subjectDN="+subjectDN);
					cryptokit.GetSealImage().then(function (response) {
						sealImage = response.result;
						console.log("sealImage="+sealImage);
						savePdf(subjectDN, sealImage);
			        }).catch(function (response) {
			        	cryptokit.GetLastErrorDesc().then(function (response) {
			                if(response.result.indexOf("印章不存在") != -1){
			                	savePdf(subjectDN, "");
			                }else{
			                	ShowErrorInfo(response);
			                }
			            });
	                });
				});
			}).catch(function (response) {
				ShowErrorInfo(response);
            });
		}else{
			//if(!isSupportCFCA()){
			//	alert("中国金融认证中心（CFCA）数字证书签名确认方式仅支持在IE(8及以上)、edge、360、搜狗浏览器下使用。");
			//}

			certificate = new Certificate();
			certificate.init();

			if(certificate.getCFCAMsgSignCertificate()){
				subjectDN = CryptoAgent.GetSignCertInfo("SubjectDN");
				console.log("subjectDN="+subjectDN);
				sealImage = certificate.getSealImage();
				console.log("sealImage="+sealImage);

				if(sealImage < 0){
					ShowErrorInfo(sealImage);
				}else{
					savePdf(subjectDN, sealImage);
				}
			}
		}
	}
});



$("#confirmButton2").bind("click",function(event){
	ht.loading.open();
	var signType = $("input[name='signType']:checked").val();
	console.log(signType);
	
	var data={
		authStartTime:$("#authStartTime").val(),
		authEndTime:$("#authEndTime").val(),
		bankOrgId:$("#bankOrgId").val(),
		signType:"0"
	}
	
	$.ajax({
		url:baseUrl+"/hos/auth/savePdf/",
		data:data,
		type:'post',
        success(res){
			console.log("authNo="+res.data.authNo);

			if("500" == res.code){
				alert(res.msg);
				ht.loading.close();
	        	return false;
			}
			
			parent.setAuthInfo(res.data.authNo, res.data.id, res.data.aid);
        	ht.loading.close();
        },
        fail(err){
            console.log("err="+err.msg);
            ht.loading.close();
        }
    });
});



function savePdf(subjectDN,sealImage){
	var data={
		authStartTime:$("#authStartTime").val(),
		authEndTime:$("#authEndTime").val(),
		bankOrgId:$("#bankOrgId").val(),
		subjectDN:subjectDN,
		sealImage:sealImage,
		signType:"1"
	}
	$.ajax({
		url:baseUrl+"/hos/auth/savePdf/",
		data:data,
		type:'post',
        success(res){
			console.log("CfcaHash="+res.data.cfcaHash);
			console.log("CfcaId="+res.data.cfcaId);

			if("500" == res.code){
				alert(res.msg);
				ht.loading.close();
	        	return false;
			}

			var browser = browserInfo();
			if("Edge"==browser.name || "Edge(Chromium)"==browser.name){
				console.log("res.data.cfcaHash="+res.data.cfcaHash);
				cryptokit.SignHashMsgPKCS7Detached(res.data.cfcaHash,"SHA-1").then(function(response){
					var cfcaSignature = response.result;

					var data={
		   				subjectDN:subjectDN,
						cfcaId:res.data.cfcaId,
						cfcaHash:res.data.cfcaHash,
						cfcaSignature:cfcaSignature,
						filePath:res.data.filePath,
						id:res.data.id
					}
					$.ajax({
						url:baseUrl+"/hos/auth/signAuth/",
						data:data,
						type:'post',
				        success(res){
				        	parent.setAuthInfo(res.data.authNo, res.data.id, res.data.aid);
				        	ht.loading.close();
				        },
				        fail(err){
				            console.log("err="+err.msg);
				            ht.loading.close();
				        }
				    });

				}).catch(function (response) {
            		self.ShowErrorInfo(response);
		        	return false;
                });
			}else{
				var cfcaSignature = certificate.getHashMsgSignature(res.data.cfcaHash);

				var data={
	   				subjectDN:subjectDN,
					cfcaId:res.data.cfcaId,
					cfcaHash:res.data.cfcaHash,
					cfcaSignature:cfcaSignature,
					filePath:res.data.filePath,
					id:res.data.id
				}
				$.ajax({
					url:baseUrl+"/hos/auth/signAuth/",
					data:data,
					type:'post',
			        success(res){console.log(res.data);
			        	parent.setAuthInfo(res.data.authNo, res.data.id, res.data.aid);
			        	ht.loading.close();
			        },
			        fail(err){
			            console.log("err="+err.msg);
			            ht.loading.close();
			        }
			    });
			}
        },
        fail(err){
            console.log("err="+err.msg);
            ht.loading.close();
        }
    });
}

function isSupportCFCA(){
	 for (var key in navigator.plugins) {
     	if (navigator.plugins[key].filename == 'npCryptoKit.CRCRFSP.x86.dll') {
          	return true;
     	}
 	}
	return false;
}

function browserInfo(){
	var res = {
        name: "",
        version: "",
    };
    var reg;
    var userAgent = self.navigator.userAgent;

    if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) {
        res.name = "Edge";
        res.version = reg[1];
    }
    else if (reg = /edg\/([\d\.]+)/i.exec(userAgent)) {
        res.name = "Edge(Chromium)";
        res.version = reg[1];
    }
    return res;
}

var pwdErrCount = 3;
function ShowErrorInfo(response) {
	var self = this;
    if(null == response){
        alert("操作失败，请联系管理员");
    }else if(1 == response.errorcode) {
		alert("签章功能无法使用，原因可能为：\n1.浏览器版本不适用，中国金融认证中心（CFCA）数字证书签名确认方式支持在Edge浏览器（Edge80-最新）、非IE浏览器（360及搜狗中支持NPAPI的浏览器）、IE浏览器（IE10-11）下使用；\n2.如浏览器版本适用，可能为当前未安装加载项/数字证书控件，请前往我的园地—数字证书绑定指引页面重新操作绑定流程再进行签章。");
    }else{ // host error
    	if(response == -1){
    		//alert("操作已被用户取消");
		}else if(response == -2){
			pwdErrCount--;
			alert("PIN码输入错误，请重新输入（还有"+pwdErrCount+"次机会）");
		}else if(response == -3){
			alert("请检查U盾状态是否正常，如有问题请拨打客服电话：400-009-0001");
		}else{
			self.cryptokit.GetLastErrorDesc().then(function (response) {console.log("result="+response.result);
                var errorInfo = ""+response.result;
                if(errorInfo.indexOf("提供的 PIN 不对") != -1){
                	pwdErrCount--;
        			alert("PIN码输入错误，请重新输入（还有"+pwdErrCount+"次机会）");
                }else if(errorInfo.indexOf("0xa00718a4") != -1){
                	alert("UKEY可能已被锁定，请检查后再尝试。");
                }else if(errorInfo.indexOf("0xa0071001") != -1){
					alert("请检查U盾状态是否正常，如有问题请拨打客服电话：400-009-0001");
				}else{
                	alert(errorInfo);
                }
            });
		}
    }
    ht.loading.close();
}
</script>
</html>